package com.springboot.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: lzh
 */
public class QrCodeUtil {

    // 默认二维码宽度
    public static final int WIDTH = 300;
    // 默认二维码高度
    public static final int HEIGHT = 300;
    // 默认二维码文件格式
    public static final String FORMAT = "png";

    // 二维码参数
    public static final Map<EncodeHintType, Object> HINTS = new HashMap<EncodeHintType, Object>();
    //初始化编码格式等参数
    static {
        // 字符编码
        HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
        HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码与图片边距
        HINTS.put(EncodeHintType.MARGIN, 2);
    }

    public static ByteArrayOutputStream writeToStream(String content) throws WriterException, IOException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, byteArrayOutputStream);
        return byteArrayOutputStream;
    }
}
